package com.mall.shopping.services;

import com.mall.shopping.IHomeService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.HomePageResponse;
import com.mall.shopping.dto.PanelContentItemDto;
import com.mall.shopping.dto.PanelDto;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;


@Service
@Slf4j
public class HomeServiceImpl implements IHomeService {

    @Autowired
    PanelMapper panelMapper;


    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ContentConverter contentConverter;


    @Override
    public HomePageResponse homepage() {

        log.info("Begin HomeServiceImpl.homepage");
        HomePageResponse response=new HomePageResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        try {
            // 先找到首页板块中所有的类目
            Example panelExample = new Example(Panel.class);
            panelExample.createCriteria()
                    .andEqualTo("position", 0)
                    .andEqualTo("status", 1);
            panelExample.setOrderByClause("sort_order");
            List<Panel> panels = panelMapper.selectByExample(panelExample);

            HashSet<PanelDto> panelContentItemDtos = new HashSet<>();

            // 获取每个类目的商品
            panels.stream()
                    .forEach(panel -> {
                                List<PanelContentItem> panelContentItems
                                        // 获取每个版块的商品信息
                                        = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                        PanelDto panelDto = contentConverter.panen2Dto(panel);
                        List<PanelContentItemDto> ItemDtos
                                = contentConverter.panelContentItem2Dto(panelContentItems);
                        panelDto.setPanelContentItems(ItemDtos);
                        panelContentItemDtos.add(panelDto);

                    });

            response.setPanelContentItemDtos(panelContentItemDtos);
        } catch (Exception e) {
            log.error("HomeServiceImpl.homepage Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }
}
